package com.dj.tool;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Platform;


import cn.com.zte.ant.model.AntModelLoader;
import cn.com.zte.ant.model.AntModelObjectPartner;
import cn.com.zte.ngbc.base.util.JsonUtil;
import cn.com.zte.ngbc.engine.data.DataArea;
import cn.com.zte.ngbc.frw.model.ModelFileAware;
import cn.com.zte.ngbc.frw.model.datainterface.DataInterfaceElement;
import cn.com.zte.ngbc.frw.model.datainterface.DataInterfaceField;
import cn.com.zte.ngbc.frw.model.datainterface.DataInterfaceFields;
import cn.com.zte.ngbc.frw.model.tran.FlowTransactionConf;
import console.ConsoleFactory;

public class ReadModel {
	
	public static Map models=new HashMap();
	
	public  static String[]  FileList() {
		String path = null;
        path = Platform.getLocation().toString();
        List list = new ArrayList();
//        list.add("One");
//        list.add("Two");
//        list.add("Three");
        
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IProject[] iproject=  root.getProjects();
	    Set<File> ret11 = new HashSet();
		Map listWithoutDup=new HashMap();
        for (IProject iProject2 : iproject) {
        		iProject2.getLocation();
        		path= iProject2.getFullPath().toString()+"  "+iProject2.getLocation().toString();
        		// ConsoleFactory.printToConsole("1111"+path, true);
 			    Collection<File> filesCollection = FileUtils.listFiles(new File(iProject2.getLocation().toString()), new String[] { "xml"}, true);
 				if (filesCollection.size() >0 && filesCollection !=null) {
 					for (File file : filesCollection) {
 						String xmlFilePath = file.getAbsolutePath();
 						if(xmlFilePath.indexOf("/src/main/resources/")>0)
 						{	
 							listWithoutDup.put(xmlFilePath.substring(xmlFilePath.indexOf("/src/main/resources/")), xmlFilePath);
 						    // ret11.add(new File(xmlFilePath));
 						}
 					}
 				} 
		}
			for (Object object : listWithoutDup.values()) {
					System.out.println(object);
					ret11.add(new File((String) object));
			}
		    Set<File> reta = new HashSet();
		    //reta.add(new File(fullpath));
		    AntModelLoader m = new AntModelLoader(ret11,reta);
		    AntModelObjectPartner.setModelLoader(m);
		    for (Object model1 : m.getSourceModels()){
		    	 ModelFileAware modelFile = (ModelFileAware)model1;
		    	 if(modelFile instanceof FlowTransactionConf){
		    		 FlowTransactionConf modelFile1=(FlowTransactionConf)modelFile;
		    		 System.out.println( modelFile.getId()+":"+modelFile1.getLongname());
		    		 list.add(modelFile.getId()+":"+modelFile1.getLongname());
		    		 models.put(modelFile.getId()+":"+modelFile1.getLongname(), modelFile1);
		    	 }
		    	 
		    }

		return (String[]) list.toArray(new String[list.size()]);
		
	}
	
	
	public  static String  context(FlowTransactionConf tran) {
        List<DataInterfaceElement>  input	=tran.getDataInterface().getInput().getElements();
        DataArea req2 = DataArea.buildWithEmpty();

        for (DataInterfaceElement ele  :   input) {
          processField(ele,req2,0,new HashMap() );
        }
        
        req2.getSystem().add("prcscd", tran.getId());
	    req2.getSystem().add("pckgsq", "00730058");
	  

	    req2.getCommReq().add("farendma", "9999");
	    req2.getCommReq().add("temp", ""); 
	    req2.getHeader().add("head", "600");      
    	
        System.out.println( JsonUtil.format(req2.getData()));
       String c=  JsonUtil.format(req2.getData());
		return format(c);
		
		
	}
	
	
	
	  private static void  processField(DataInterfaceElement ele,DataArea data,int a,Map map)
	  {
	    if ((ele instanceof DataInterfaceField))
	    {
	    	if(a==0){
	    		data.getInput().add(ele.getId(), "");
	    	}else{
	    		map.put(ele.getId(), "");
	    	}
	    }
	    else
	    {	      
	      DataInterfaceFields fields = (DataInterfaceFields)ele;
	      if (fields.getElements() != null)
	      {
	        List<DataInterfaceElement> childs = (List<DataInterfaceElement>) fields.getElements();
	        Map fieldsmap=new HashMap();
	        List ddd= new ArrayList();
	        System.out.println(fields.getId());
	        for (DataInterfaceElement e : childs)
	        {
	          processField(e,data,1,fieldsmap);
	        }
	        ddd.add(fieldsmap);
	        data.getInput().add(fields.getId(),  ddd);
	      }
	    }
	  }
	
	
	   public static  String  send(String  data,String ip,String port) throws IOException
	    {
			    	 DataArea req = DataArea.buildWithEmpty();
				   	  req.getLinkReq().add("scidxx", "201");
				   	  req.getLinkReq().add("scname", "ZTE");
				   	  req.getLinkReq().add("trancd", "TA001");
				   	  String datah = JsonUtil.formatPkg(req.getData());
				   	  
				   	  String data2 ="               00020150411040856665        0006001921680750010008008001                                         	   "+data;//JsonUtil.formatPkg(data.getData());
			   	
			        Socket socket = new Socket(ip,Integer.parseInt(port));
			        socket.setSoTimeout(20000);
			        InputStream input = socket.getInputStream();
			        OutputStream output = socket.getOutputStream();
			   //     System.out.println("开始发送请求: '" + inputs + "'");
			        writeMessage(output,datah);
//			        System.out.println("开始接收应答");
			        String outputs = readMessage(input, output);	
//			        System.out.println(outputs);
			       // ConsoleFactory.printToConsole("...load coding config "+configfilepath, true);
			        System.out.println("开始发送请求: '" +  data + "'");    //JsonUtil.formatPkg(data.getData())
			        writeMessage(output,data2);
			        System.out.println("开始接收应答");
			        String outputs1 = readMessage(input, output);	
			        System.out.println(outputs1.substring(116));
			        return format(outputs1.substring(116));

	    }    
	    
	    
	    public static void writeMessage(OutputStream output, String ret) throws IOException
	    {
	      byte[] bytes = ret.getBytes("UTF-8");
	      String lenPrefix = "00000000" + bytes.length;
	      lenPrefix = lenPrefix.substring(lenPrefix.length() - 8); 
	      PrintWriter writer =   new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
	      System.out.println(lenPrefix);
	      writer.print(lenPrefix);
	      writer.print(ret);
	      writer.flush();
	    }
	    public static String readMessage(InputStream input, OutputStream output) throws IOException
	    {
	      byte[] bytes = read(input, 8);
	      if (bytes == null) return null;
	      String length = new String(bytes, "UTF-8");
	      try {
	        int len = Integer.parseInt(length.trim());
	        bytes = read(input, len);
	        if (bytes == null) throw new IOException("Can't read any message:" + len);
	        String msg = new String(bytes, "UTF-8");
	        return msg; } catch (NumberFormatException e) {
	      }
	      throw new IOException("Illegal package length: '" + length + "'.");
	    } 
	    public static byte[] read(InputStream input, int len) throws IOException
	    {
	      byte[] cbuf = new byte[len];
	      int off = 0;
	      int trytimes = 1;
	      while ((off < cbuf.length) && (trytimes < 50)) {
	        trytimes++;
	        len = input.read(cbuf, off, cbuf.length - off);
	  
	        if (len == -1)
	        {
	          if (off == 0) return null;
	          throw new IOException("Can't read '" + cbuf.length + "' bytes from socket, read:\n" );
	        }
	        off += len;
	      }
	  
	      if (off < cbuf.length)
	        throw new IOException("Exceed to max try times for reading socket: '" + trytimes + "', read:\n" );
	      return cbuf;
	    }	
	    
	    
	    /**
	     * 得到格式化json数据  退格用\t 换行用\r
	     */
	    public static String format(String jsonStr) {
	      int level = 0;
	      StringBuffer jsonForMatStr = new StringBuffer();
	      for(int i=0;i<jsonStr.length();i++){
	        char c = jsonStr.charAt(i);
	        if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){
	          jsonForMatStr.append(getLevelStr(level));
	        }
	        switch (c) {
	        case '{': 
	        case '[':
	          jsonForMatStr.append(c+"\n");
	          level++;
	          break;
	        case ',': 
	          jsonForMatStr.append(c+"\n");
	          break;
	        case '}':
	        case ']':
	          jsonForMatStr.append("\n");
	          level--;
	          jsonForMatStr.append(getLevelStr(level));
	          jsonForMatStr.append(c);
	          break;
	        default:
	          jsonForMatStr.append(c);
	          break;
	        }
	      }
	      
	      return jsonForMatStr.toString();

	    }
	    
	    private static String getLevelStr(int level){
	        StringBuffer levelStr = new StringBuffer();
	        for(int levelI = 0;levelI<level ; levelI++){
	          levelStr.append("\t");
	        }
	        return levelStr.toString();
	      } 
	    

}
